package com.wanpinghui.wphlibrary;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.wanpinghui.wphlibrary.common.GrobalListener;
import com.wanpinghui.wphlibrary.model.addrbook.AddrbookServiceImp;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.business.BusinessServiceImp;
import com.wanpinghui.wphlibrary.model.db.manager.CartDbManager;
import com.wanpinghui.wphlibrary.model.message.MessageServiceImp;
import com.wanpinghui.wphlibrary.model.oauth.OAuthServiceImp;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.object.ObjectServiceImp;
import com.wanpinghui.wphlibrary.model.order.OrderServiceImp;
import com.wanpinghui.wphlibrary.model.product.CartCountChangeListener;
import com.wanpinghui.wphlibrary.model.product.ProductServiceImp;
import com.wanpinghui.wphlibrary.model.user.UserInfoServiceImp;
import com.yunshl.yunshllibrary.storage.MDBManager;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.callback.FailOrExceptionType;


/***
 * 功能描述:library的对象，方法拦截等管理类
 * 作者:qiujialiu
 * 时间:2017/5/27
 ***/

public class WPHLibrary {
    private static final String TAG = "HDLibrary";
    private static WPHLibrary library;
    private Map<String, Object> serivceMap;
    private Context context;
    private IWXAPI mWeChat;
    private Tencent mTencent;
    private List<GrobalListener> listeners;
    private List<CartCountChangeListener> changeListeners;
    private String WXAppid;

    private WPHLibrary() {
        serivceMap = new HashMap<>();
        listeners = new ArrayList<>();
    }

    static void init(Context context) {
        library = new WPHLibrary();
        library.context = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        MDBManager.getInstance().createDatabase("wph_supplier");
        UserBean userBean = UserInfoUtil.getUserInfo();
        if (userBean != null && userBean.getUser() != null) {
            MDBManager.getInstance().createDatabase(userBean.getUser().getId(),"wph_supplier");
        }
    }

    static void reinitDB(){
        UserBean userBean = UserInfoUtil.getUserInfo();
        if (userBean != null && userBean.getUser() != null) {
            MDBManager.getInstance().createDatabase(userBean.getUser().getId(),"wph_supplier");
        }
    }

    public static WPHLibrary getLibrary() {
        if (library == null) {
            throw new RuntimeException("please invoke HDSDK.init(app) before use this library");
        }
        return library;
    }

    public Context getContext() {
        return context;
    }

    <T> T getService(Class<T> tClass) {
        LogUtils.w("-----", tClass.getName());
        if (serivceMap.get(tClass.getName()) != null) {
            return (T) serivceMap.get(tClass.getName());
        }

        final T c = getServiceImpClass(tClass);

        final T result1 = (T) Proxy.newProxyInstance(c.getClass().getClassLoader(), c.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        LogUtils.w(TAG, "befault method " + method.getName());
                        Object obj = method.invoke(c, args);
                        LogUtils.w(TAG, "after method " + method.getName());
                        return obj;
                    }
                });
        serivceMap.put(tClass.getName(), result1);
        return result1;
    }

    public IWXAPI getWeChat() {
        return mWeChat;
    }

    public Tencent getTencent() {
        return mTencent;
    }

    public String getWeChatAppid() {
        return WXAppid;
    }

    private <T> T getServiceImpClass(Class<T> tClass) {
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.oauth.OAuthService")) {
            return (T) new OAuthServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.object.ObjectService")) {
            return (T) new ObjectServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.user.UserInfoService")) {
            return (T) new UserInfoServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.message.MessageService")) {
            return (T) new MessageServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.product.ProductService")) {
            return (T) new ProductServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.order.OrderService")) {
            return (T) new OrderServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.addrbook.AddrbookService")) {
            return (T) new AddrbookServiceImp();
        }
        if (TextUtil.equals(tClass.getName(), "com.wanpinghui.wphlibrary.model.business.BusinessService")) {
            return (T) new BusinessServiceImp();
        }
        return null;
    }


    void initWeChat(String appid) {
        this.mWeChat = WXAPIFactory.createWXAPI(context, null);
        this.mWeChat.registerApp(appid);
        WXAppid = appid;
        mWeChat.registerApp(appid);
    }

    void initTencent(String appid) {
        this.mTencent = Tencent.createInstance(appid, context);
    }


    void addGrobalListener(GrobalListener listener) {
        listeners.clear();
        listeners.add(listener);
    }

    public void onCartChange(int cartCount) {
        if (changeListeners != null && changeListeners.size() > 0) {
            for (CartCountChangeListener listener : changeListeners) {
                listener.onChange(cartCount);
            }
        }
    }

    void removeGrobalListener(GrobalListener listener) {
        if (listeners != null) {
            listeners.remove(listener);
        }
    }

    public void sendRequestFial(@FailOrExceptionType.FailType int failType , int code) {
        if (listeners != null && listeners.size() > 0) {
            for (GrobalListener listener : listeners) {
                listener.requestFial(failType, code);
            }
        }
    }

    public void lostNetwork() {
        if (listeners != null && listeners.size() > 0) {
            for (GrobalListener listener : listeners) {
                listener.networkLost();
            }
        }
    }

    public void availableNetwork() {
        if (listeners != null && listeners.size() > 0) {
            for (GrobalListener listener : listeners) {
                listener.networkAvailable();
            }
        }
    }

    public void addCartCountChangeListener(CartCountChangeListener listener) {
        if (listener == null)return;
        if (changeListeners == null) {
            changeListeners = new ArrayList<>();
        }
        changeListeners.add(listener);
        listener.onChange(CartDbManager.getInstance().getCartProductCount());
    }

    public void removeCartCountChangeListener(CartCountChangeListener listener) {
        if (changeListeners != null && listener != null) {
            changeListeners.remove(listener);
            if (changeListeners.size() == 0){
                changeListeners = null;
            }
        }
    }
}
